package com.szh.lenovo0520;

import android.app.Service;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

public class DBService extends Service {
    private static final String TAG = "DBService";
    MyDBHelper helper = new MyDBHelper(this);
    SQLiteDatabase db;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what==1) {
                ToastSuccess();
            }else {
                ToastDefault();
            }
        }
    };

    public DBService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind: ");
        MyBinder myBinder = new MyBinder();
        return myBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public class MyBinder extends Binder {
        public void CallQueryInfo(String username, String userpwd) {
            QueryInfo(username, userpwd);
        }

    }

    public void QueryInfo(final String name, final String pwd) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                    db = helper.getWritableDatabase();
                    Cursor user = db.query("user", null, "username=?", new String[]{name}, null, null, null);
                    user.moveToNext();
                    String userPwd = user.getString(user.getColumnIndex("userPwd"));
                    if (pwd.equals(userPwd)) {
                        handler.sendEmptyMessage(1);
                    } else {
                        handler.sendEmptyMessage(2);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }

    public void ToastSuccess() {
        Toast.makeText(this, "登录成功！", Toast.LENGTH_SHORT).show();
    }

    public void ToastDefault() {
        Toast.makeText(this, "登录失败！", Toast.LENGTH_SHORT).show();
    }
}
